<?php

namespace App\Admin\Forms\Config;

use App\Models\Config as Model;
use Dcat\Admin\Widgets\Dropdown;
use Dcat\Admin\Widgets\Form;
use Exception;
use Illuminate\Database\Eloquent\ModelNotFoundException;

class Config extends Form
{
    /**
     * Handle the form request.
     *
     * @param array $input
     *
     * @return mixed
     */
    public function handle(array $input)
    {
         $res = 0;
         if ($input){
             try {
                 foreach ($input as $key=>$value){
                     $model = Model::where('name',$key)->first();
                     $model->value = is_array($value)?json_encode($value):$value;
                     $res += $model->save();
                 }
             }catch (ModelNotFoundException|Exception $e){
                 return $this->response()->error($e->getMessage())->refresh();
             }
         }
         return $this->response()->success($res?'保存成功.':'暂无修改.')->refresh();
    }

    /**
     * Build a form here.
     */
    public function form()
    {
        $this->tab("基础配置",function (){
            $this->number("cancel_hours","距离预约时间小于多少小时不允许取消洗车订单(小时)")->default(0);
            $this->number("confirm_hours","商品订单发货后,多少天后自动确认收货完成(天)")->default(0);
            $this->number("finish_day",'退款期限(下单后)多久后结算分销(天)')->default(0);
            $this->decimal("courier_fee","快递运费")->width(3)->default(0);
            $this->rate("platform_rate","门店每笔交易-平台分配比例")->width(3)->default(0);
        });
        $this->tab("加盟合作",function (){
//            $this->ckeditor("join_text","加盟合作详情信息");
            $this->array("join_text","加盟合作详情信息",function ($table){
                $table->text("title","标题");
                $table->ckeditor("value","详情信息");
            });
        });
        $this->tab("海报设置",function (){
            $this->column(6,function (){
                $this->image("poster_enter_img","海报入口图")->autoUpload()->removable(false)->name('poster_enter_img.png')->help("尺寸:347*69");
            });
            $this->column(6,function (){
                $this->image("poster_img","海报背景图")->autoUpload()->help("尺寸:539*958")->default();
            });
        });
    }

    /**
     * The data of the form.
     *
     * @return array
     */
    public function default()
    {
        return $this->getDefault();
    }

    protected function getDefault(){
        $row = Model::query()->pluck("value","name")->toArray();
        return $row;
    }
}
